package logic

import (
	"context"
	"encoding/json"
	"newgoods/goodsrpc/goodsrpc"
	"newgoods/goodsrpc/goodsrpcclient"
	"newgoods/goodsrpc/internal/svc"
	"newgoods/models/cache"
	"newgoods/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *goodsrpc.GoodsListRequest) (*goodsrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line
	/*
			SELECT
		  goods.id AS goods_id,
		  goods.`name`,
		  goods.price,
		  goods.stock,
		  goods.image,
		  classes.`name` as classes_name,
		  classes.created_at
		FROM
		  goods
		  LEFT JOIN classes ON classes.id = goods.class_id
	*/
	//主表是什么
	//关联那个表
	var GoodList []*goodsrpcclient.GoodsList

	result, _ := cache.Rdb.Get(l.ctx, "goodList").Result()
	if result == "" {
		mysql.DB.Model(&mysql.Goods{}).
			Select("goods.id AS goods_id",
				"goods.`name` as goods_name",
				"goods.price",
				"goods.stock",
				"goods.image",
				"classes.`name` as class_name",
				"classes.created_at").
			Joins("LEFT JOIN classes ON classes.id = goods.class_id").Find(&GoodList)
		marshal, _ := json.Marshal(GoodList)
		cache.Rdb.Set(l.ctx, "goodList", marshal, time.Minute*120)
	} else {
		json.Unmarshal([]byte(result), &GoodList)
	}
	//result, _ := cache.Rdb.Get(l.ctx, "goodsList").Result()

	////if result == "" {
	//mysql.DB.Debug().Model(&mysql.Goods{}).
	//	Select("goods.id as goods_id",
	//		"goods.name as goods_name",
	//		"goods.price",
	//		"goods.stock",
	//		"goods.image",
	//		"classes.name as class_name",
	//		"goods.created_at").
	//	Joins("LEFT JOIN classes ON goods.class_id = classes.id").Find(&goodsLists)

	//	marshal, _ := json.Marshal(goodsLists)
	//	cache.Rdb.Set(l.ctx, "goodsList", marshal, time.Minute*120)
	//} else {
	//	json.Unmarshal([]byte(result), &goodsLists)
	//}

	return &goodsrpc.GoodsListResponse{
		List: GoodList,
	}, nil
}
